package fge;

import com.mxgraph.model.mxCell;
import javax.swing.JTree;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;

public class TreeView implements TreeSelectionListener {

	private Main mm;
	public JTree tree;
	private boolean updating = false;
	
	public TreeView(Main _mm) {
		this.mm = _mm;

		mxCell rootcell = (mxCell) mm.graph.getDefaultParent();
		tree = new JTree(new TreeHierarchyModel(rootcell));
		tree.setRootVisible(false);
		tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
		tree.addTreeSelectionListener(this);
		
		DefaultTreeCellRenderer renderer = new DefaultTreeCellRenderer();
		renderer.setLeafIcon(null);
		tree.setCellRenderer(renderer);
	}

	public void valueChanged(TreeSelectionEvent e) {
		if (updating) return;
		Object node = tree.getLastSelectedPathComponent();
		if (!(node instanceof mxCell)) return;
		mxCell cell = (mxCell)node;

		mm.selectAndShow(cell);
	}

	void update() {
		updating = true; 
		TreePath tmp = this.tree.getSelectionPath();
		((TreeHierarchyModel) this.tree.getModel()).reload();
		this.tree.setSelectionPath(tmp); 
		updating = false;
	}
}
